/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sw2asteriskjava;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.asteriskjava.manager.AuthenticationFailedException;
import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.ManagerEventListener;
import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.manager.action.CoreShowChannelsAction;
import org.asteriskjava.manager.action.OriginateAction;
import org.asteriskjava.manager.action.StatusAction;
import org.asteriskjava.manager.event.CdrEvent;
import org.asteriskjava.manager.event.CoreShowChannelsCompleteEvent;
import org.asteriskjava.manager.event.ManagerEvent;
import org.asteriskjava.manager.response.ManagerResponse;

/**
 *
 * @author gustavo.higa
 */
public class AsteriskManagerUtils implements ManagerEventListener {

    private static int timeout = 30000;
    private static boolean end = false;
    private static int activeChannels = -1;

    /**
     * @param aEnd the end to set
     */
    public static void setEnd() {
        end = true;
    }

    /**
     *
     * @param channel Canal de origen, para el caso LOCAL/anexo, el anexo debe existir
     * @param context Contexto, normalemente from internal
     * @param sound Ruta del archivo de sonido
     * @param extension Anexo destino de la llamada
     */
    public void generateCallwRecordedSound(String channel, String context, String sound, String extension) {
        try {
            ManagerConnection managerConnection = AsteriskManagerConnection.getManagerConnection();
            OriginateAction originateAction;
            ManagerResponse originateResponse;
            originateAction = new OriginateAction();
            originateAction.setChannel(channel);
            originateAction.setContext(context);
            originateAction.setApplication("Playback");
            originateAction.setData(sound);
            originateAction.setCallerId("asterisk-java");
            originateAction.setExten(extension);
            originateAction.setPriority(new Integer(1));
            originateAction.setTimeout(new Integer(30000));
            managerConnection.login();
            originateResponse = managerConnection.sendAction(originateAction, timeout);

            System.out.println(originateResponse.getResponse());
            Thread.sleep(10000);
            managerConnection.logoff();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void listenForCdrEvent() {
        try {
            ManagerConnection managerConnection = AsteriskManagerConnection.getManagerConnection();
            managerConnection.addEventListener(this);
            managerConnection.login();
            managerConnection.sendAction(new StatusAction());
            while (true) {
                if (end) {
                    break;
                } else {
                    Thread.currentThread().sleep(1000);
                }
            }
            end = false;
            managerConnection.logoff();
        } catch (Exception ex) {
            Logger.getLogger(AsteriskManagerUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onManagerEvent(ManagerEvent event) {
        //System.out.println("EVENT: " + event);
        if (event instanceof CdrEvent) {
            System.out.println("CDR ID =: " + ((CdrEvent) event).getUniqueId());

            actualizarDatosBD(((CdrEvent) event).getUniqueId());

        }
        if (event instanceof CoreShowChannelsCompleteEvent) {
            activeChannels = ((CoreShowChannelsCompleteEvent) event).getListitems();
        }
    }

    public int getActiveChannels() {
        try {
            activeChannels = -1;
            CoreShowChannelsAction coreShowChannelsAction = new CoreShowChannelsAction();
            ManagerConnection managerConnection = AsteriskManagerConnection.getManagerConnection();
            managerConnection.addEventListener(this);
            managerConnection.login();
            managerConnection.sendAction(coreShowChannelsAction);
            managerConnection.logoff();
            while (activeChannels < 0) {
                Thread.currentThread().sleep(1000);
            }
            System.out.println("Canales activos: "+String.valueOf(activeChannels));
            return activeChannels;
        } catch (Exception ex) {
            Logger.getLogger(AsteriskManagerUtils.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        }
    }

    public void actualizarDatosBD(String CdrID){
        System.out.println("Actualizando datos en BD");
    }

}
